package com.topvision.myviewtest.kotlin.part1

import java.io.File

/**
 *
 * @author lucy
 * @date 2018-05-30 18:01
 * @description //习惯用法
 */

// DTOs
data class Customer(var name: String, var age: Int)

// 函数默认参数
fun foo(a: Int = 1, b: Double = 2.0): Double = a * b

// 过滤list
var list = listOf(1, 2, 3, 4, 5)
val positives1 = list.filter { x -> x > 3 }
//or
val positives2 = list.filter { it > 3 }

// 创建map
var map = mapOf("name" to "LiXiaoLong", "age" to 20, "sex" to "male")

// 分割线
fun printLine() {
    println()
    println("--------------------------------")
}

// 扩展函数
fun String.spaceToUp() {

}

// 创建单例(object)
object Resource {
    val name = "NAME"
}

// 单表达式
fun single1() = 32

// 等价于
fun single2(): Int {
    return 32
}

fun main(args: Array<String>) {

    println(foo())
    println(foo(3, 4.0))
//    out: 2.0
//         12.0

    println("positives1 = $positives1")
    println("positives2 = $positives2")

//    out: positives1 = [4, 5]
//         positives2 = [4, 5]

//    map遍历
    for ((k, v) in map) {
        println("key = $k, value = $v")
    }
//    out: key = name, value = LiXiaoLong
//         key = age, value = 20
//         key = sex, value = male

    // 闭包区间
    for (x1 in 0..10) {
        print("x1 = $x1 |")
    }
    //out: x1 = 0 |x1 = 1 |x1 = 2 |x1 = 3 |x1 = 4 |x1 = 5 |x1 = 6 |x1 = 7 |x1 = 8 |x1 = 9 |x1 = 10 |

    printLine()

    // 半开区间
    for (x2 in 0 until 10) {
        print("x2 = $x2 |")
    }
    //out: x2 = 0 |x2 = 1 |x2 = 2 |x2 = 3 |x2 = 4 |x2 = 5 |x2 = 6 |x2 = 7 |x2 = 8 |x2 = 9 |

    printLine()

    // 跳步遍历
    for (x3 in 0..10 step 2) {
        print("x3 = $x3 |")
    }
    //out: x3 = 0 |x3 = 2 |x3 = 4 |x3 = 6 |x3 = 8 |x3 = 10 |
    printLine()

    // 可使用自定义函数
    "aa".spaceToUp()

    // 使用单例
    val a = Resource.name

    // If not null 缩写
    val listFiles = File("test").listFiles()
    println(listFiles?.size)
    //out: null

    printLine()

    // if not null and else 缩写
    println(listFiles?.size ?: "empty")
    // out: empty

    printLine()

    // if null 执行一个语句
//    val emails = mapOf("a" to 1)
//    println(emails["b"] ?: throw IllegalStateException("Email is missing"))
    // out: 异常 Email is missing

    printLine()

    // 在可能会空的集合中取第一元素
    val listOf = listOf(Any())
    println(listOf.firstOrNull() ?: "empty")
}

